package com.mall.thirdparth.pay.util;

import com.wechat.pay.java.core.util.IOUtil;
import com.wechat.pay.java.core.util.PemUtil;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.Base64Utils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.Random;

/**
 * @ClassName WXPayUtils
 * @Author ymx
 * @Description 微信支付工具类
 * @Date 2023/12/21
 **/
public class WXPayUtils {

    private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    private static final Random RANDOM = new SecureRandom();

    /**
     * 获取签名
     * @param signatureStr
     * @param privateKey
     * @return
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     * @throws SignatureException
     * @throws IOException
     * @throws URISyntaxException
     */
    public static String getSign(String signatureStr,String privateKey) throws InvalidKeyException,
            NoSuchAlgorithmException, SignatureException, IOException, URISyntaxException {
        // 证书密钥
        String privateKeyStr = IOUtil.toString(new ClassPathResource(privateKey).getInputStream());
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKeyFromString(privateKeyStr);
        Signature sign = Signature.getInstance("SHA256withRSA");
        sign.initSign(merchantPrivateKey);
        sign.update(signatureStr.getBytes(StandardCharsets.UTF_8));
        return Base64Utils.encodeToString(sign.sign());
    }

    /**
     * 获取随机字符串：NonceStr
     * @return String 随机字符串
     */
    public static String generateNonceStr() {
        char[] nonceChars = new char[32];
        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        return new String(nonceChars);
    }

}
